package com.school.test.search.function.service;

import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.school.test.search.function.assist.IndexAssist;
import com.school.test.search.function.datamodel.TestModel;
import org.bson.Document;

import java.util.Collection;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.regex.Pattern;

/**
 * @author 马洁
 * @date 2020/1/4 - 12:27
 */
public class StudentService extends BaseTeaAndStuService {

    public Collection<? extends String> searchName(Pattern regStr) {
        TreeSet<String> resStudentSet = new TreeSet<>();
        // 将学生班级中查找到的学生班级加入结果集
        searchInExamListByRegStr("classes", regStr, resStudentSet);
        return resStudentSet;
    }

    public TestModel getTestsByName(String classesName, boolean haveMakeUpExam) {
        // 找到有关该学生的考试搜索结果, 并按照时间戳进行排序
        FindIterable<Document> testSearchList =
                IndexAssist.getExam()
                        .find(Filters.regex("classes", classesName))
                        .sort(Sorts.ascending("timestamp"));

        Predicate<Document> predicate = null;

        if (!haveMakeUpExam) {
            String grade = classesName.substring(0, 2);

            predicate = doc -> doc.getList("classes", String.class)
                    .stream()
                    .noneMatch(item -> grade.compareTo(item.substring(0, 2)) < 0);
        }

        return dealTestList(testSearchList, predicate);
    }
}
